package com.gitee.minimalismstyle.fresh.common.document.controller

import com.gitee.minimalismstyle.fresh.common.core.config.FreshProperties
import com.gitee.minimalismstyle.fresh.common.core.domain.R
import com.gitee.minimalismstyle.fresh.common.document.domain.ImportStatus
import com.gitee.minimalismstyle.fresh.common.document.service.ImportService
import com.gitee.minimalismstyle.fresh.common.web.util.WebUtils
import io.swagger.annotations.Api
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse


@Api(value = "execl", tags = ["Execl操作"])
@RestController
@RequestMapping("/execl")
class ExeclController(val importService: ImportService,
                      val freshProperties: FreshProperties) {

    @GetMapping("download/template/{id}")
    fun downloadTemplate(@PathVariable id: String,
                         name : String,
                         request: HttpServletRequest,
                         response: HttpServletResponse){
        WebUtils.download(request, response, "/import/${id}.xlsx", "${name}.xlsx")
    }

    @PutMapping("import/{id}")
    fun import(@PathVariable id: String, file: MultipartFile, params: Map<String, Any>): R<ImportStatus> {
        val importStatus = importService.save(file)
        if(importStatus.success){
            importService.import(id, importStatus.fileId!! , params)
        }

        return R.success(importStatus)
    }

    @GetMapping("import/status/{id}")
    fun importStatus(@PathVariable id: Long): R<ImportStatus>{
       return importService.findStatus(id)
    }

    @GetMapping("/download/{id}")
    fun import(@PathVariable id: Long, request: HttpServletRequest, response: HttpServletResponse){
        val tempdir = freshProperties.tempdir.replaceFirst("classes:", this.javaClass.getResource("/").path)
        val tempPath = "$tempdir/import/$id.xlsx"
        WebUtils.download(request, response, tempPath, "错误信息")
    }

}